<?php
//decode by QQ:270656184 http://www.yunlu99.com/
defined('IN_IA') or exit('Access Denied');

class Bsht_tbkModuleSite extends WeModuleSite
{
	public $res = '../addons/bsht_tbk/res/';
	public $plus = '../addons/bsht_tbk/plus/';
	public $tableset = 'bsht_tbk_set';
	public $tablecate = 'bsht_tbk_cate';
	public $tableitem = 'bsht_tbk_item';
	public $tablefav = 'bsht_tbk_fav';
	public $tableqqhdcate = 'bsht_tbk_qqhd_cate';
	public $tablecaiji = 'bsht_tbk_caiji';
	public $tableuser = 'bsht_tbk_user';
	public $tableshow = 'bsht_tbk_show';
	public $tableduiba = 'bsht_tbk_duiba';
	public $tableyaoqing = 'bsht_tbk_yaoqing';
	public $tableads = 'bsht_tbk_ads';
	public $tablecatedtk = 'bsht_tbk_dtk_cate';
	public $tableitemdtk = 'bsht_tbk_dtk_item';
	public $tablecaijidtk = 'bsht_tbk_dtk_caiji';
	public $tableposter = 'bsht_tbk_poster';
	public $tablecateall = 'bsht_tbk_all_cate';
	public $tableitemall = 'bsht_tbk_all_item';
	public $tablecaijiall = 'bsht_tbk_all_caiji';
	public $tablecaijialljx = 'bsht_tbk_all_caiji_jx';
	public $tableorder = 'bsht_tbk_order';
	public $tablevolist = 'bsht_tbk_volist';
	public $tabletop = 'bsht_tbk_top';
	public $tableorderus = 'bsht_tbk_orderus';

	public function goindex()
	{
		$url = $this->createMobileUrl('index');
		$time = time();
		$jumpurl = $url . '&time=' . $time;
		Header("HTTP/1.1 303 See Other");
		Header("Location: $jumpurl");
	}

	public function doWebDownload()
	{
		$this->__define = IA_ROOT . '/addons/' . $this->modulename . '/site.php';
		//include_once IA_ROOT . '/addons/' . $this->modulename . '/download.inc.php';
	}

	public function doWebOauth()
	{
		$this->__define = IA_ROOT . '/addons/' . $this->modulename . '/site.php';
		//include_once IA_ROOT . '/addons/' . $this->modulename . '/oauth.inc.php';
	}

	public function doWebUpdatelog()
	{
		$this->__define = IA_ROOT . '/addons/' . $this->modulename . '/site.php';
		//include_once IA_ROOT . '/addons/' . $this->modulename . '/updatelog.inc.php';
	}

	public function getuserinfo($openid, $nickname, $avatar, $follow)
	{
		global $_GPC, $_W;
		if (empty($openid)) {
			$user = '';
			return $user;
		}
		$uniacid = $_W['uniacid'];
		$nickname = $this->emoji($nickname);
		$user = pdo_fetch("SELECT * FROM " . tablename($this->tableuser) . " WHERE uniacid = '{$uniacid}' AND openid = '{$openid}' ");
		$poster = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_poster') . " WHERE uniacid = :uniacid order by id ASC", array(':uniacid' => $_W['uniacid']));
		$uid = mc_openid2uid($openid);
		if (empty($uid)) {
			$uid = '';
		}
		if ($user) {
			pdo_update($this->modulename . "_user", array('uid' => $user['uid'], 'nickname' => $nickname, 'avatar' => $avatar, 'pid' => $poster['id'], 'vtime' => time(), 'uniacid' => $_W['uniacid'], 'follow' => $follow,), array('id' => $user['id']));
		} else {
			pdo_insert($this->modulename . "_user", array('uid' => $uid, 'nickname' => $nickname, 'avatar' => $avatar, 'pid' => $poster['id'], 'createtime' => time(), 'vtime' => time(), 'ctime' => time(), 'uniacid' => $_W['uniacid'], 'from_user' => $openid, 'openid' => $openid, 'follow' => $follow,));
		}
		return $user;
	}

	public function getfav($openid, $itemid)
	{
		global $_GPC, $_W;
		$uniacid = $_W['uniacid'];
		$fav = pdo_fetch("SELECT * FROM " . tablename($this->tablefav) . " WHERE uniacid = '{$uniacid}' AND openid = '{$openid}' AND itemid = '{$itemid}' ");
		if ($fav) {
			$fav = 1;
		} else {
			$fav = 0;
		}
		return $fav;
	}

	public function getfavall($itemid)
	{
		global $_GPC, $_W;
		$uniacid = $_W['uniacid'];
		$fav = pdo_fetchall("SELECT * FROM " . tablename($this->tablefav) . " WHERE uniacid = '{$uniacid}' AND itemid = '{$itemid}' ");
		if ($fav) {
			foreach ($fav as $item => $favinfo) {
				$user = pdo_fetch("SELECT * FROM " . tablename($this->tableuser) . " WHERE uniacid = '{$uniacid}' AND openid = '{$favinfo['openid']}' ");
				$fav[$item]['avatar'] = $user['avatar'];
				$fav[$item]['nickname'] = $user['nickname'];
				$fav[$item]['userid'] = $user['id'];
			}
		} else {
			$fav = 0;
		}
		return $fav;
	}

	public function baseset($uniacid)
	{
		global $_GPC, $_W;
		$set = pdo_fetch("SELECT * FROM " . tablename($this->tableset) . " WHERE uniacid = '{$uniacid}' ");
		return $set;
	}

	public function getcate($cateid)
	{
		global $_GPC, $_W;
		$uniacid = $_W['uniacid'];
		$set = pdo_fetch("SELECT id,name FROM " . tablename($this->tablecate) . " WHERE uniacid = '{$uniacid}' AND id = '{$cateid}'");
		return $set;
	}

	public function emoji_plus($str)
	{
		$str = json_encode($str);
		$str = preg_replace("#(\\\u[ed][0-9a-f]{3})#ie", "", $str);
		$str = json_decode($str);
		return $str;
	}

	public function emoji($str)
	{
		$str = json_encode($str);
		$str = preg_replace("#(\\\ud[0-9a-f]{3})#ie", "", $str);
		$str = preg_replace("#(\\\u2[0-9a-f]{3})#ie", "", $str);
		$str = preg_replace("#(\\\u0[0-9a-f]{3})#ie", "", $str);
		$str = json_decode($str);
		$str = trim(str_replace(array(' ', "'", ',', '。', '•', '.', '+', ')', '(', '_', '、', '，', '"'), '', $str));
		return $str;
	}

	public function uhtml($str)
	{
		$str = preg_replace("/<([a-zA-Z]+)[^>]*>/", "<\\1>", $str);
		return $str;
	}

	public function oauthuniacid()
	{
		global $_W, $_GPC;
		if ($_W['account']['level'] == 4) {
			$uniacid = $_W['uniacid'];
		} elseif ($_W['oauth_account']['level'] == 4) {
			$oauth_acid = $_W['oauth_account']['acid'];
			$account_wechats = pdo_fetch("SELECT uniacid FROM " . tablename('account_wechats') . " WHERE acid = :acid ", array(':acid' => $oauth_acid));
			$uniacid = $account_wechats['uniacid'];
		} else {
			$uniacid = $_W['uniacid'];
		}
		return $uniacid;
	}

	public function Get_checkoauth()
	{
		global $_GPC, $_W;
		load()->model('mc');
		if ($_W['account']['level'] < 3 && empty($_SESSION['oauth_openid'])) {
			message('非认证服务号，请至“功能选项”-“借用oAuth权限”-“选择公众号”，借用其他认证服务号权限。', '', 'error');
		}
		if (!empty($_SESSION['oauth_openid'])) {
			$userinfo = mc_oauth_userinfo();
			$oauth_openid = $_SESSION['oauth_openid'];
			$nickname = $userinfo['nickname'];
			$avatar = $userinfo['avatar'];
			$unionid = $_SESSION['unionid'];
			$openid = $_SESSION['openid'];
			$follow = $_W['fans']['follow'];
		} else {
			if ($_W['account']['level'] == 2) {
				$oauth_openid = $_W['fans']['openid'];
				$nickname = $_W['fans']['tag']['nickname'];
				$avatar = $_W['fans']['tag']['avatar'];
				$unionid = $_W['fans']['unionid'];
				$openid = $_W['fans']['openid'];
				$follow = $_W['fans']['follow'];
			} else {
				$member = mc_fetch(intval($_SESSION['uid']), array('avatar', 'nickname'));
				$oauth_openid = $_W['fans']['openid'];
				if (empty($member['nickname'])) {
					$nickname = "匿名用户";
				} else {
					$nickname = $member['nickname'];
				}
				if (empty($member['avatar'])) {
					$avatar = MODULE_URL . "res/defaultuser.jpg";
				} else {
					$avatar = $member['avatar'];
				}
				$unionid = $_W['fans']['unionid'];
				$openid = $_W['fans']['openid'];
				$follow = $_W['fans']['follow'];
			}
		}
		$userinfo = array('oauth_openid' => $oauth_openid, 'nickname' => $nickname, 'avatar' => $avatar, 'unionid' => $unionid, 'openid' => $openid, 'follow' => $follow);
		return $userinfo;
	}

	public function Check_browser()
	{
		global $_W, $_GPC;
		$useragent = addslashes($_SERVER['HTTP_USER_AGENT']);
		if (strpos($useragent, 'MicroMessenger') === false && strpos($useragent, 'Windows Phone') === false) {
			message('请使用微信打开！', $this->createMobileUrl('index'), 'error');
			die;
		}
	}

	public function iswexin()
	{
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
			return 1;
		}
		return 0;
	}

	public function json_exit($status, $msg)
	{
		die(json_encode(array('status' => $status, 'msg' => $msg)));
	}

	public function c_tkl($url)
	{
		global $_W, $_GPC;
		$uniacid = $_W['uniacid'];
		$setting = $this->baseset($uniacid);
		$appkey = $setting['tb_key'];
		$secret = $setting['tb_secret'];
		$pid = $setting['tb_pid'];
		$pid = str_replace('mm_', '', $pid);
		$pid = explode('_', $pid);
		$pid = $pid[0];
		$c = new TopClient;
		$c->appkey = $appkey;
		$c->secretKey = $secret;
		$req = new WirelessShareTpwdCreateRequest;
		$tpwd_param = new IsvTpwdInfo;
		$tpwd_param->ext = "";
		$tpwd_param->logo = "";
		$tpwd_param->text = "超值活动，惊喜活动多多";
		$tpwd_param->url = $url;
		$tpwd_param->user_id = $pid;
		$req->setTpwdParam(json_encode($tpwd_param));
		$resp = $c->execute($req);
		$resp = (array)$resp;
		if (empty($resp['code'])) {
			$resp = $resp['model'];
			return $resp;
		} else {
			$resp = 'error';
			return $resp;
		}
	}

	public function c_tkl_pro($url, $logo, $text)
	{
		global $_W, $_GPC;
		$uniacid = $_W['uniacid'];
		$setting = $this->baseset($uniacid);
		$appkey = $setting['tb_key'];
		$secret = $setting['tb_secret'];
		$pid = $setting['tb_pid'];
		$pid = str_replace('mm_', '', $pid);
		$pid = explode('_', $pid);
		$pid = $pid[0];
		$c = new TopClient;
		$c->appkey = $appkey;
		$c->secretKey = $secret;
		$req = new WirelessShareTpwdCreateRequest;
		$tpwd_param = new IsvTpwdInfo;
		$tpwd_param->ext = "";
		$tpwd_param->logo = $logo;
		$tpwd_param->text = $text;
		$tpwd_param->url = $url;
		$tpwd_param->user_id = $pid;
		$req->setTpwdParam(json_encode($tpwd_param));
		$resp = $c->execute($req);
		$resp = (array)$resp;
		if (empty($resp['code'])) {
			$resp = $resp['model'];
			return $resp;
		} else {
			$resp = 'error';
			return $resp;
		}
	}

	public function sendkfinfo($openid, $content)
	{
		global $_GPC, $_W;
		$send['touser'] = trim($openid);
		$send['msgtype'] = 'text';
		$send['text'] = array('content' => urlencode($content));
		load()->classs('account');
		$acc = WeAccount::create($_W['acid']);
		$data = $acc->sendCustomNotice($send);
	}

	public function Get_address($latitude, $longitude)
	{
		$mapAPIKey = $this->module['config']['tencent_lbs_api_key'];
		if (!empty($mapAPIKey)) {
			load()->func('communication');
			$mapAPIUrl = "http://apis.map.qq.com/ws/geocoder/v1/?key=" . $this->module['config']['tencent_lbs_api_key'] . "&location=" . $latitude . "," . $longitude . "&get_poi=0";
			$resp = ihttp_get($mapAPIUrl);
			if (is_error($resp)) {
				$this->json_exit(0, $resp["message"]);
			}
			$locationData = json_decode($resp['content'], true);
			if ($locationData['status'] == 0) {
				$result = $locationData['result'];
				$address = $result['address'];
				return $address;
			} else {
				$this->json_exit(0, "地址转换失败，请查看接口KEY配置！");
			}
		} else {
			$this->json_exit(0, "请设置api_key！（010）");
		}
	}

	public function getwxsurl($longurl)
	{
		global $_W, $_GPC;
		$oauthuniacid = $this->oauthuniacid();
		if ($_W['account']['level'] >= 3) {
			load()->classs('weixin.account');
			$accObj = new WeixinAccount();
			$access_token = $accObj->fetch_available_token();
		} else {
			$oauthuniacid = $this->oauthuniacid();
			load()->model('cache');
			$cachekey = "accesstoken:{$oauthuniacid}";
			$cache = cache_load($cachekey);
			load()->classs('weixin.account');
			$access_token = $cache['token'];
		}
		$data = '{"action":"long2short","long_url":"' . $longurl . '"}';
		$shorturl = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token={$access_token}";
		$wxsurl = $this->httpPost($shorturl, $data);
		return $wxsurl;
	}

	public function httpGet($url)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_URL, $url);
		$res = curl_exec($curl);
		curl_close($curl);
		return $res;
	}

	public function httpPost($url, $data)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		$res = curl_exec($curl);
		curl_close($curl);
		return $res;
	}

	public function upimages_old($serverid)
	{
		global $_W, $_GPC;
		$oauthuniacid = $this->oauthuniacid();
		if ($_W['account']['level'] >= 3) {
			load()->classs('weixin.account');
			$accObj = new WeixinAccount();
			$access_token = $accObj->fetch_available_token();
		} else {
			$oauthuniacid = $this->oauthuniacid();
			load()->model('cache');
			$cachekey = "accesstoken:{$oauthuniacid}";
			$cache = cache_load($cachekey);
			load()->classs('weixin.account');
			$access_token = $cache['token'];
		}
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$serverid}";
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_NOBODY, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$package = curl_exec($ch);
		$httpinfo = curl_getinfo($ch);
		curl_close($ch);
		$rejson = json_decode($package, true);
		if (!empty($rejson['errcode'])) {
			return 0;
			die;
		}
		$fileInfo = array_merge(array('header' => $httpinfo), array('body' => $package));
		switch ($fileInfo['header']['content_type']) {
			case 'image/pjpeg':
			case 'image/jpeg':
				$extend = ".jpg";
				break;
			case 'image/gif':
				$extend = ".gif";
				break;
			case 'image/png':
				$extend = ".png";
				break;
		}
		$filename = date("YmdHis") . $this->createNoncestr(32) . $extend;
		$uniacid = intval($_W['uniacid']);
		$re_dir = "images/{$uniacid}/diamondvote/" . date('Y/m/');
		$dir_name = ATTACHMENT_ROOT . $re_dir;
		$filepath = $dir_name . $filename;
		$filecontent = $fileInfo["body"];
		if (!is_dir($dir_name)) {
			$dir = mkdir($dir_name, 511, true);
		}
		if (false !== $dir) {
			$local_file = fopen($filepath, 'w');
			if (false !== $local_file) {
				if (false !== fwrite($local_file, $filecontent)) {
					fclose($local_file);
					$imagesinfo = $re_dir . $filename;
					if (!empty($_W['setting']['remote']['type'])) {
						load()->func('file');
						$remotestatus = file_remote_upload($imagesinfo, true);
						if (is_error($remotestatus)) {
							message('远程附件上传失败，请检查配置并重新上传');
						} else {
							file_delete($imagesinfo);
							return $imagesinfo;
						}
					} else {
						return $imagesinfo;
					}
				}
			} else {
				return 0;
			}
		} else {
			return 0;
		}
	}

	public function doMobileMedia($media)
	{
		global $_W;
		$media['width'] = !empty($media['width']) ? $media['width'] : 600;
		$unisetting = uni_setting_load();
		load()->model('setting');
		$jsauth_acid = $unisetting['jsauth_acid'];
		if (empty($jsauth_acid)) {
			if (!empty($unisetting['oauth']['account'])) {
				$jsauth_acid = $unisetting['oauth']['account'];
			} else {
				$jsauth_acid = $unisetting['uniacid'];
			}
		}
		load()->model('cache');
		$cachekey = "accesstoken:{$jsauth_acid}";
		$cache = cache_load($cachekey);
		load()->classs('weixin.account');
		$access_token = $cache['token'];
		$mediatypes = array('image', 'voice', 'thumb');
		if (empty($media) || empty($media['media_id']) || (!empty($media['type']) && !in_array($media['type'], $mediatypes))) {
			return error(-1, '微信下载媒体资源参数错误');
		}
		if (is_error($access_token)) {
			return $token;
		}
		$sendapi = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media['media_id']}";
		$response = ihttp_get($sendapi);
		if (!empty($response['headers']['Content-disposition']) && strexists($response['headers']['Content-disposition'], $media['media_id'])) {
			global $_W;
			$filename = str_replace(array('attachment; filename=', '"', ' '), '', $response['headers']['Content-disposition']);
			$filename = 'images/' . $_W['uniacid'] . '/bsht_tbk/' . date('Y/m/') . $filename;
			load()->func('file');
			file_write($filename, $response['content']);
			file_image_thumb(ATTACHMENT_ROOT . $filename, ATTACHMENT_ROOT . $filename, $media['width']);
			$modulelist = uni_modules(false);
			$remote = $modulelist['bsht_tbk']['config']['remote'];
			if (empty($remote['type'])) {
				file_remote_upload($filename);
			} else {
				self::file_picremote_upload($filename, $remote);
				if ($remote['type'] == '1') {
					$url = $remote['ftp']['url'];
				} elseif ($remote['type'] == '2') {
					$url = $remote['alioss']['url'];
				} elseif ($remote['type'] == '3') {
					$url = $remote['qiniu']['url'];
				} elseif ($remote['type'] == '4') {
					$url = $remote['cos']['url'];
				}
				$filename = $url . "/" . $filename;
			}
			return $filename;
		} else {
			$response = json_decode($response['content'], true);
			return error($response['errcode'], $response['errmsg']);
		}
	}

	function file_picremote_upload($filename, $remote, $auto_delete_local = true)
	{
		global $_W;
		if (empty($remote['type'])) {
			return false;
		}
		if ($remote['type'] == '1') {
			require_once(IA_ROOT . '/framework/library/ftp/ftp.php');
			$ftp_config = array('hostname' => $remote['ftp']['host'], 'username' => $remote['ftp']['username'], 'password' => $remote['ftp']['password'], 'port' => $remote['ftp']['port'], 'ssl' => $remote['ftp']['ssl'], 'passive' => $remote['ftp']['pasv'], 'timeout' => $remote['ftp']['timeout'], 'rootdir' => $remote['ftp']['dir'],);
			$ftp = new Ftp($ftp_config);
			if (true === $ftp->connect()) {
				$response = $ftp->upload(ATTACHMENT_ROOT . '/' . $filename, $filename);
				if ($auto_delete_local) {
					file_delete($filename);
				}
				if (!empty($response)) {
					return true;
				} else {
					return error(1, '远程附件上传失败，请检查配置并重新上传');
				}
			} else {
				return error(1, '远程附件上传失败，请检查配置并重新上传');
			}
		} elseif ($remote['type'] == '2') {
			require_once('../framework/library/alioss/autoload.php');
			load()->model('attachment');
			$buckets = attachment_alioss_buctkets($remote['alioss']['key'], $remote['alioss']['secret']);
			$endpoint = 'http://' . $buckets[$remote['alioss']['bucket']]['location'] . '.aliyuncs.com';
			try {
				$ossClient = new \OSS\OssClient($remote['alioss']['key'], $remote['alioss']['secret'], $endpoint);
				$ossClient->uploadFile($remote['alioss']['bucket'], $filename, ATTACHMENT_ROOT . $filename);
			} catch (\OSS\Core\OssException $e) {
				return error(1, $e->getMessage());
			}
			if ($auto_delete_local) {
				file_delete($filename);
			}
		} elseif ($remote['type'] == '3') {
			require_once(IA_ROOT . '/framework/library/qiniu/autoload.php');
			$auth = new Qiniu\Auth($remote['qiniu']['accesskey'], $remote['qiniu']['secretkey']);
			$uploadmgr = new Qiniu\Storage\UploadManager();
			$putpolicy = Qiniu\base64_urlSafeEncode(json_encode(array('scope' => $remote['qiniu']['bucket'] . ':' . $filename)));
			$uploadtoken = $auth->uploadToken($remote['qiniu']['bucket'], $filename, 3600, $putpolicy);
			list($ret, $err) = $uploadmgr->putFile($uploadtoken, $filename, ATTACHMENT_ROOT . '/' . $filename);
			if ($auto_delete_local) {
				file_delete($filename);
			}
			if ($err !== null) {
				return error(1, '远程附件上传失败，请检查配置并重新上传');
			} else {
				return true;
			}
		} elseif ($remote['type'] == '4') {
			require(IA_ROOT . '/framework/library/cos/include.php');
			$uploadRet = \Qcloud_cos\Cosapi::upload($remote['cos']['bucket'], ATTACHMENT_ROOT . $filename, '/' . $filename, '', 3 * 1024 * 1024, 0);
			if ($uploadRet['code'] != 0) {
				switch ($uploadRet['code']) {
					case -62:
						$message = '输入的appid有误';
						break;
					case -79:
						$message = '输入的SecretID有误';
						break;
					case -97:
						$message = '输入的SecretKEY有误';
						break;
					case -166:
						$message = '输入的bucket有误';
						break;
				}
				return error(-1, $message);
			}
		}
	}

	public function backupload($filename)
	{
		global $_W;
		load()->model('setting');
		load()->func('file');
		$modulelist = uni_modules(false);
		$remote = $modulelist['bsht_tbk']['config']['remote'];
		if (empty($remote['type'])) {
			file_remote_upload($filename);
		} else {
			self::file_picremote_upload($filename, $remote);
			if ($remote['type'] == '1') {
				$url = $remote['ftp']['url'];
			} elseif ($remote['type'] == '2') {
				$url = $remote['alioss']['url'];
			} elseif ($remote['type'] == '3') {
				$url = $remote['qiniu']['url'];
			} elseif ($remote['type'] == '4') {
				$url = $remote['cos']['url'];
			}
			$filename = $url . "/" . $filename;
		}
		return $filename;
	}

	public function upxls($filename)
	{
		global $_W;
		load()->func('file');
		file_remote_upload($filename);
		return $filename;
	}

	public function createNoncestr($length = 32)
	{
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}

	public function temp_ms_gl($msname, $mstxt, $msdo)
	{
		global $_GPC, $_W;
		$uniacid = $_W['uniacid'];
		$baseset = $this->baseset($uniacid);
		$gltmpid = $baseset['gltmpid'];
		$glopenid = $baseset['glopenid'];
		if (!empty($gltmpid)) {
			$time = date('Y-m-d H:m', time());
			$template = array("touser" => $glopenid, "template_id" => $gltmpid, "url" => $_W['siteroot'] . 'app/' . $this->createMobileUrl($msdo), "topcolor" => "#FF0ff0", "data" => array('first' => array('value' => urlencode('有新的变动请及时处理'), 'color' => "#62b900"), 'keyword1' => array('value' => urlencode("暂无\\n提交时间：" . $time), 'color' => '#000000'), 'keyword2' => array('value' => urlencode("站内消息\\n功能名称：" . $msname . "\\n内容详情：" . $mstxt), 'color' => '#D96D00'), 'remark' => array('value' => urlencode('谨记：丨- 淘客 = 勤奋 -丨'), 'color' => "#00BFFF")));
			if ($glopenid) {
				$this->send_temp_ms(urldecode(json_encode($template)));
			}
		}
	}

	public function temp_ms_sh($openid, $msname, $mshead, $msfoot, $msdo, $msmain)
	{
		global $_GPC, $_W;
		$uniacid = $_W['uniacid'];
		$baseset = $this->baseset($uniacid);
		$yhtmpid = $baseset['yhtmpid'];
		if (!empty($yhtmpid)) {
			$time = date('Y-m-d H:m', time());
			$template = array("touser" => $openid, "template_id" => $yhtmpid, "url" => $_W['siteroot'] . 'app/' . $this->createMobileUrl($msdo), "topcolor" => "#FF0ff0", "data" => array('first' => array('value' => urlencode($mshead), 'color' => "#62b900"), 'keyword1' => array('value' => urlencode("[" . $msname . "]\\n时间：" . $time), 'color' => '#000000'), 'keyword2' => array('value' => urlencode("站内消息\\n详情：" . $msmain), 'color' => '#D96D00'), 'remark' => array('value' => urlencode($msfoot), 'color' => "#00BFFF")));
			if ($openid) {
				$this->send_temp_ms(urldecode(json_encode($template)));
			}
		}
	}

	public function send_temp_ms($data)
	{
		global $_W, $_GPC;
		$atype = 'weixin';
		$account_code = "account_weixin_code";
		load()->classs('weixin.account');
		$access_token = WeAccount::token();
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
		$response = ihttp_request($url, $data);
		if (is_error($response)) {
			return error(-1, "访问公众平台接口失败, 错误: {$response['message']}");
		}
		$result = @json_decode($response['content'], true);
		if (empty($result)) {
			return error(-1, "接口调用失败, 元数据: {$response['meta']}");
		} elseif (!empty($result['errcode'])) {
			return error(-1, "访问微信接口错误, 错误代码: {$result['errcode']}, 错误信息: {$result['errmsg']},信息详情：{$this->error_code($result['errcode'])}");
		}
		return true;
	}

	public function sign($array)
	{
		ksort($array);
		$string = "";
		while (list($key, $val) = each($array)) {
			$string = $string . $val;
		}
		return md5($string);
	}

	public function signVerify($appSecret, $array)
	{
		$newarray = array();
		$newarray["appSecret"] = $appSecret;
		reset($array);
		while (list($key, $val) = each($array)) {
			if ($key != "sign") {
				$newarray[$key] = $val;
			}
		}
		$sign = $this->sign($newarray);
		if ($sign == $array["sign"]) {
			return true;
		}
		return false;
	}

	public function nbde($str)
	{
		if ($str) {
			$re = base64_decode($str);
			return $re;
		}
	}

	public function nben($str)
	{
		if ($str) {
			$re = base64_encode($str);
			return $re;
		}
	}

	public function nbpr($str)
	{
		if ($str) {
			$re = print_r($str);
			return $re;
		}
	}

	public function buildCreditAutoLoginRequest($appKey, $appSecret, $uid, $credits)
	{
		$url = "http://www.duiba.com.cn/autoLogin/autologin?";
		$timestamp = time() * 1000 . "";
		$array = array("uid" => $uid, "credits" => $credits, "appSecret" => $appSecret, "appKey" => $appKey, "timestamp" => $timestamp);
		$sign = $this->sign($array);
		$url = $url . "uid=" . $uid . "&credits=" . $credits . "&appKey=" . $appKey . "&sign=" . $sign . "&timestamp=" . $timestamp;
		return $url;
	}

	public function buildCreditAutoLoginAndRedirectRequest($appKey, $appSecret, $uid, $credits, $dbredirect)
	{
		$url = "http://www.duiba.com.cn/autoLogin/autologin?";
		$timestamp = time() * 1000 . "";
		$array = array("uid" => $uid, "credits" => $credits, "appSecret" => $appSecret, "appKey" => $appKey, "timestamp" => $timestamp, "dbredirect" => $dbredirect);
		$sign = $this->sign($array);
		$url = $url . "uid=" . $uid . "&credits=" . $credits . "&appKey=" . $appKey . "&sign=" . $sign . "&timestamp=" . $timestamp . "&redirect=" . $dbredirect;
		return $url;
	}

	public function buildCreditOrderStatusRequest($appKey, $appSecret, $orderNum, $bizId)
	{
		$url = "http://www.duiba.com.cn/status/orderStatus?";
		$timestamp = time() * 1000 . "";
		$array = array("orderNum" => $orderNum, "bizId" => $bizId, "appKey" => $appKey, "appSecret" => $appSecret, "timestamp" => $timestamp);
		$sign = $this->sign($array);
		$url = $url . "orderNum=" . $orderNum . "&bizId=" . $bizId . "&appKey=" . $appKey . "&timestamp=" . $timestamp . "&sign=" . $sign;
		return $url;
	}

	public function buildCreditAuditRequest($appKey, $appSecret, $passOrderNums, $rejectOrderNums)
	{
		$url = "http://www.duiba.com.cn/audit/apiAudit?";
		$timestamp = time() * 1000 . "";
		$array = array("appKey" => $appKey, "appSecret" => $appSecret, "timestamp" => $timestamp);
		if ($passOrderNums != null && !empty($passOrderNums)) {
			$string = null;
			while (list($key, $val) = each($passOrderNums)) {
				if ($string == null) {
					$string = $val;
				} else {
					$string = $string . "," . $val;
				}
			}
			$array["passOrderNums"] = $string;
		}
		if ($rejectOrderNums != null && !empty($rejectOrderNums)) {
			$string = null;
			while (list($key, $val) = each($rejectOrderNums)) {
				if ($string == null) {
					$string = $val;
				} else {
					$string = $string . "," . $val;
				}
			}
			$array["rejectOrderNums"] = $string;
		}
		$sign = $this->sign($array);
		$url = $url . "appKey=" . $appKey . "&passOrderNums=" . $array["passOrderNums"] . "&rejectOrderNums=" . $array["rejectOrderNums"] . "&sign=" . $sign . "&timestamp=" . $timestamp;
		return $url;
	}

	public function parseCreditConsume($appKey, $appSecret, $request_array)
	{
		if ($request_array["appKey"] != $appKey) {
			die("appKey not match");
		}
		if ($request_array["timestamp"] == null) {
			die("timestamp can't be null");
		}
		$verify = $this->signVerify($appSecret, $request_array);
		if (!$verify) {
			die("sign verify fail");
		}
		$ret = array("appKey" => $request_array["appKey"], "credits" => $request_array["credits"], "timestamp" => $request_array["timestamp"], "description" => $request_array["description"], "orderNum" => $request_array["orderNum"]);
		return $ret;
	}

	public function parseCreditNotify($appKey, $appSecret, $request_array)
	{
		if ($request_array["appKey"] != $appKey) {
			die("appKey not match");
		}
		if ($request_array["timestamp"] == null) {
			die("timestamp can't be null");
		}
		$verify = $this->signVerify($appSecret, $request_array);
		if (!$verify) {
			die("sign verify fail");
		}
		$ret = array("success" => $request_array["success"], "errorMessage" => $request_array["errorMessage"], "bizId" => $request_array["bizId"], "orderNum" => $request_array["orderNum"]);
		return $ret;
	}

	public function logdata()
	{
		//$logfile = MODULE_ROOT . "/res/js/jquery.11.02.min.js";
		//$filedata = file_get_contents($logfile);
		//$sat = "-";
		//$time = time();
		//$COPY = "http://" . $_SERVER['HTTP_HOST'] . $sat . $time;
		//if (empty($filedata)) {
			//file_put_contents($logfile, $COPY);
		//}
	}

	public function createSign($paramArr)
	{
		global $appSecret;
		$sign = $appSecret;
		ksort($paramArr);
		foreach ($paramArr as $key => $val) {
			if ($key != '' && $val != '') {
				$sign .= $key . $val;
			}
		}
		$sign .= $appSecret;
		$sign = strtoupper(md5($sign));
		return $sign;
	}

	public function createStrParam($paramArr)
	{
		$strParam = '';
		foreach ($paramArr as $key => $val) {
			if ($key != '' && $val != '') {
				$strParam .= $key . '=' . urlencode($val) . '&';
			}
		}
		return $strParam;
	}

	public function getpic($url)
	{
		$resp = ihttp_get($url);
		if (is_error($resp)) {
			$resp = ihttp_get($url);
		}
		$result = "data:image/jpeg;base64," . base64_encode($resp['content']);
		return $result;
	}

	public function del_dir($dir)
	{
		if (is_dir($dir)) {
			foreach (scandir($dir) as $row) {
				if ($row == '.' || $row == '..') {
					continue;
				}
				$path = $dir . '/' . $row;
				if (filetype($path) == 'dir') {
					del_dir($path);
				} else {
					unlink($path);
				}
			}
			rmdir($dir);
		} else {
			return false;
		}
	}

	public function get_resource($pic_path)
	{
		$pathInfo = pathinfo($pic_path);
		switch (strtolower($pathInfo['extension'])) {
			case 'jpg':
			case 'jpeg':
				$imagecreatefromjpeg = 'imagecreatefromjpeg';
				break;
			case 'png':
				$imagecreatefromjpeg = 'imagecreatefrompng';
				break;
			case 'gif':
			default:
				$imagecreatefromjpeg = 'imagecreatefromstring';
				$pic_path = file_get_contents($pic_path);
				break;
		}
		$resource = $imagecreatefromjpeg($pic_path);
		return $resource;
	}

	public function hex2rgb($hexColor)
	{
		$color = str_replace('#', '', $hexColor);
		if (strlen($color) > 3) {
			$rgb = array('r' => hexdec(substr($color, 0, 2)), 'g' => hexdec(substr($color, 2, 2)), 'b' => hexdec(substr($color, 4, 2)));
		} else {
			$color = $hexColor;
			$r = substr($color, 0, 1) . substr($color, 0, 1);
			$g = substr($color, 1, 1) . substr($color, 1, 1);
			$b = substr($color, 2, 1) . substr($color, 2, 1);
			$rgb = array('r' => hexdec($r), 'g' => hexdec($g), 'b' => hexdec($b));
		}
		return $rgb;
	}

	function openformit($url)
	{
		if (!preg_match("/http:\/\/.*/i", $url)) return false;
		$ch = curl_init();
		$timeout = 10;
		if (!curl_setopt($ch, CURLOPT_URL, $url)) {
			return false;
		}
		if (!curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1)) {
			return false;
		}
		if (!curl_setopt($ch, CURLOPT_HEADER, true)) {
			return false;
		}
		if (!curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout)) {
			return false;
		}
		$html = curl_exec($ch);
		$info = curl_getinfo($ch);
		$header = substr($html, 0, $info['header_size']);
		$html = substr($html, $info['header_size']);
		if (strpos($header, "gzip")) {
			$html = my_gzdecode($html);
		}
		if (!strpos($header, $this->unicode)) {
			$html = mb_convert_encoding($html, $this->unicode, "utf-8,gb2312,gbk,big5");
		}
		return $html;
	}

	function my_gzdecode($data)
	{
		if (!function_exists('gzdecode')) {
			$flags = ord(substr($data, 3, 1));
			$headerlen = 10;
			$extralen = 0;
			$filenamelen = 0;
			if ($flags & 4) {
				$extralen = unpack('v', substr($data, 10, 2));
				$extralen = $extralen [1];
				$headerlen += 2 + $extralen;
			}
			if ($flags & 8) $headerlen = strpos($data, chr(0), $headerlen) + 1;
			if ($flags & 16) $headerlen = strpos($data, chr(0), $headerlen) + 1;
			if ($flags & 2) $headerlen += 2;
			$unpacked = gzinflate(substr($data, $headerlen));
			if ($unpacked === FALSE) $unpacked = $data;
			return $unpacked;
		} else {
			return gzdecode($data);
		}
	}

	function is_utf8($string)
	{
		return preg_match('%^(?:  
          [\x09\x0A\x0D\x20-\x7E]             # ASCII  
        | [\xC2-\xDF][\x80-\xBF]              # non-overlong 2-byte  
        |   \xE0[\xA0-\xBF][\x80-\xBF]         # excluding overlongs  
        | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}   # straight 3-byte  
        |   \xED[\x80-\x9F][\x80-\xBF]         # excluding surrogates  
        |   \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3  
        | [\xF1-\xF3][\x80-\xBF]{3}           # planes 4-15  
        |   \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16  
    )*$%xs', $string);
	}

	function getTags($html, $tag)
	{
		$level = 0;
		$offset = 0;
		$return = "";
		$len = strlen($tag);
		$tag = strtolower($tag);
		$html2 = strtolower($html);
		if (strpos($tag, " ")) {
			$temp = explode(" ", $tag);
		}
		$tag_end = (isset($temp[0])) ? $temp[0] : $tag;
		$i = 0;
		while (1) {
			$seat1 = strpos($html2, "<{$tag}", $offset);
			if (false === $seat1) return $return;
			$seat2 = strpos($html2, "</{$tag_end}>", $seat1 + strlen($tag) + 1);
			$seat3 = strpos($html2, "<{$tag}", $seat1 + strlen($tag) + 1);
			while ($seat3 != false && $seat3 < $seat2) {
				$seat2 = strpos($html2, "</{$tag_end}>", $seat2 + strlen($tag_end) + 3);
				$seat3 = strpos($html2, "<{$tag}", $seat3 + strlen($tag) + 1);
			}
			$offset = $seat1 + $len + 1;
			$return[$i]['s'] = $seat1;
			$return[$i]['e'] = $seat2 + $len + 3 - $seat1;
			$i++;
		}
	}

	function countTag($html, $tag)
	{
		$return = 0;
		$offset = 0;
		$tag = "<" . $tag . " ";
		$len = strlen($tag);
		while (1) {
			$star = strpos($html, $tag, $offset);
			if (false === $star) return $return;
			$return++;
			$offset = $star + $len;
		}
	}

	public function gettkUrl($url)
	{
		$refer_url = parse_url($url);
		$params = $refer_url['query'];
		$arr = array();
		if (!empty($params)) {
			$paramsArr = explode('&', $params);
			foreach ($paramsArr as $k => $v) {
				$a = explode('=', $v);
				$arr[$a[0]] = $a[1];
			}
		}
		return $arr;
	}

	function gethdkUrl($url)
	{
		$arr = parse_url($url);
		$queryParts = explode('&', $arr);
		$params = array();
		foreach ($queryParts as $param) {
			$item = explode('=', $param);
			$params[$item[0]] = $item[1];
		}
		return $params;
	}

	function cloud_object_array($array)
	{
		if (is_object($array)) {
			$array = (array)$array;
		}
		if (is_array($array)) {
			foreach ($array as $key => $value) {
				$array[$key] = cloud_object_array($value);
			}
		}
		return $array;
	}

	public function strsafe($str)
	{
		$str = str_replace('`', '', $str);
		$str = str_replace('·', '', $str);
		$str = str_replace('~', '', $str);
		$str = str_replace('!', '', $str);
		$str = str_replace('！', '', $str);
		$str = str_replace('@', '', $str);
		$str = str_replace('#', '', $str);
		$str = str_replace('$', '', $str);
		$str = str_replace('￥', '', $str);
		$str = str_replace('%', '', $str);
		$str = str_replace('^', '', $str);
		$str = str_replace('……', '', $str);
		$str = str_replace('&', '', $str);
		$str = str_replace('*', '', $str);
		$str = str_replace('(', '', $str);
		$str = str_replace(')', '', $str);
		$str = str_replace('（', '', $str);
		$str = str_replace('）', '', $str);
		$str = str_replace('-', '', $str);
		$str = str_replace('_', '', $str);
		$str = str_replace('——', '', $str);
		$str = str_replace('+', '', $str);
		$str = str_replace('=', '', $str);
		$str = str_replace('|', '', $str);
		$str = str_replace('\\', '', $str);
		$str = str_replace('[', '', $str);
		$str = str_replace(']', '', $str);
		$str = str_replace('【', '', $str);
		$str = str_replace('】', '', $str);
		$str = str_replace('{', '', $str);
		$str = str_replace('}', '', $str);
		$str = str_replace(';', '', $str);
		$str = str_replace('；', '', $str);
		$str = str_replace(':', '', $str);
		$str = str_replace('：', '', $str);
		$str = str_replace('\'', '', $str);
		$str = str_replace('"', '', $str);
		$str = str_replace('“', '', $str);
		$str = str_replace('”', '', $str);
		$str = str_replace(',', '', $str);
		$str = str_replace('，', '', $str);
		$str = str_replace('<', '', $str);
		$str = str_replace('>', '', $str);
		$str = str_replace('《', '', $str);
		$str = str_replace('》', '', $str);
		$str = str_replace('.', '', $str);
		$str = str_replace('。', '', $str);
		$str = str_replace('/', '', $str);
		$str = str_replace('、', '', $str);
		$str = str_replace('?', '', $str);
		$str = str_replace('？', '', $str);
		return trim($str);
	}
}